<template>
  <el-dialog width="80%" :close-on-click-modal="false" :title="title" :model-value="isShow" @open="onOpen">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="66px">
      <el-form-item style="margin-bottom: 0" label="角色" prop="parentId">

        <el-tree ref="tree" default-expand-all :data="options" show-checkbox node-key="id"
          @check-change="handleCheckChange" :props="props" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSave">确认</el-button>
    </template>
  </el-dialog>
</template>

<script>

import { getProjectRoles } from "@/api/admin/project";
import {  bindRoles } from "@/api/admin/user";
import { getRolesByUserId } from "@/api/admin/role";

export default {
  components: {},
  props: {
    data: {
      required: true,
      type: String,
      default: "",
    },
    isShow: {
      require: true,
      type: Boolean,
      default: false,
    },
    title: {
      require: true,
      type: String,
      default: "",
    },
  },
  emits: ['onChange','update:isShow'],
  data() {
    return {
      form: {},
      rules: {},
      options: [],
      props: {
        label: "name",
        children: "roles",
      },
    };
  },
  mounted() {
    getProjectRoles({}).then((res) => {
      this.options = res.result;
    });
  },
  methods: {
    async onOpen() {
      getRolesByUserId(this.data).then((res) => {
        let result = res.result;
        let roleIds = result.map((t) => t.id);
        this.$refs.tree.setCheckedKeys(roleIds);
      });
    },
    async onSave() {
      let data = {
        userId: this.data,
        roleIds: this.$refs.tree.getCheckedKeys(true),
      };
      bindRoles(data).then((res) => {
        this.$emit("onChange", this.form);
        this.$emit("update:isShow", false)
      });
    },
    onCancel() {
      this.$emit("update:isShow", false)
    },
    onClose() { },
    handleCheckChange() { },
  },
  watch: {
    data: async function () { },
  },
};
</script>


